package com.laolang.pluto.framework.config.security.handler;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.laolang.pluto.common.core.domain.common.R;
import com.laolang.pluto.common.util.ServletKit;
import com.laolang.pluto.framework.config.security.pojo.LoginUser;
import com.laolang.pluto.framework.config.security.service.TokenService;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * @author laolang
 * @date 2021-08-07 03:14
 */
@RequiredArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final TokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        // TODO 添加登录日志(异步) , 更新用户登录信息(同步)
        JSONObject jsonObject = new JSONObject();

        Object principal = authentication.getPrincipal();
        if (principal instanceof LoginUser) {
            LoginUser loginUser = (LoginUser) principal;
            loginUser.getSysUser().setPassword(null);
            String token = tokenService.createToken(loginUser);
            jsonObject.put("token", token);
        }
        ServletKit.writeJson(response, JSONUtil.toJsonStr(R.ok(jsonObject)));
    }
}
